PROJECT = "WB2_OTA"
VERSION = "1.0.0"

require"sys"
require "pins"
local a = false
local b = ""
local i = 1

function stringToHex(str)
    local hex = ""
    for i = 1, #str do
        hex = hex .. string.format("%02X ", string.byte(str, i))
    end
    return hex
end

function usbwrite(s)
    log.info("usb sent",s)
    uart.write(uart.USB, s)
end

function uartwrite(uart_ID,s)
    log.info("uart sent",uart_ID,s)
    uart.write(uart_ID, s)
end

local function usbreader()
    local data = ""
    while true do
        data = uart.read(uart.USB,1024)
        if not data or string.len(data) == 0 then break end
        uartwrite(2,data)
        if string.find(data,"AT%+HTTPCLIENTLINE") then
            log.info("进入下载程序")
            a = true
        end
    end
end

local function strget(data)
    b = b .. data
end



local function uartreader()
    local data = ""
    while true do
        data = uart.read(2,1024)
        if not data or string.len(data) == 0 then break end         --消息来的太快派出去了，这里还需要改成一个函数包装起来
        usbwrite(data)
        if a == true then
            if string.match(data,"OK\r\n") then
                log.info("收到OK，跳转，下载完成")
                log.info("b的值",#b,b)
                -- usbwrite(b)
                sys.publish("OTA_start")
            else
                log.info("将数据写入","数据长度",#data)
                --需要一个字符串拼接，将所有的数据拼接起来，然后再发进去
                strget(data)
            end
        end
    end
end

function uart_load()
    log.info("sys","开启全部虚拟串口数据透传模式")
    uart.setup(2,115200,8,uart.PAR_NONE,uart.STOP_1)--921600
    uart.on(2, "receive", uartreader)
    uart.setup(uart.USB, 0, 0, uart.PAR_NONE, uart.STOP_1)
    uart.on(uart.USB, "receive", usbreader)
    uartwrite(2,"ATE0\r\n")
    log.info('sys',"uart is running")
end

sys.taskInit(function()
    sys.wait(5000)
    pins.setup(pio.P0_19, 1)      --WIFI模块供电
    pins.setup(pio.P0_15, 1)
    uart_load()
    -- while true do
    --     log.info("==========>"..VERSION.."<==========")
    --     sys.wait(1500)
    -- end
end)

sys.taskInit(function()
    sys.waitUntil("OTA_start")
    log.info("开始进行OTA升级")
    local res =rtos.fota_start()
    sys.wait(1500)
    log.info("fota初始化",res)
    if res ==0 then
        while true do
            local stepData = string.sub(b,i,i+1460)
            i = i+1460

            local fotaProcessStatus=rtos.fota_process( stepData,#b)
            if fotaProcessStatus~=0 then
                log.info("failed","222222222222222222")
                break
            else
                log.info("processs",sProcessedLen,"/",totalLen)
                --sProcessedLen = sProcessedLen + stepData:len()
            end
            if i >= #b then
                log.info("数据收完了，退出循环")
                rtos.fota_end()
                sys.restart("重启解决")
            else
                log.info("失败了","44444444444444")
            end
        end
    else
        log.info("fota初始化失败了")
    end
end)


sys.init(0, 0)
sys.run()
